<template>
  <div class="huichuanshangpin">

    <div v-loading='loading' style="padding: 20px;">

      <div style="background: rgb(249, 249, 249); padding: 20px; color: rgb(51, 51, 51);">
                  自定义商品详情设置
                </div>
      					<div class="kflex" style="padding: 20px;">
                  <div style="width: 600px; color: rgb(51, 51, 51);">
                    <div  style="margin-bottom: 40px;">
                      <div style="margin-bottom: 20px; font-size: 14px;">商品名称</div>
                      <div><el-input v-model="all.name" placeholder="请输入标题名"></el-input></div>
                    </div>
                    <div style="margin-bottom: 40px;" class="h100">
                      <div style="margin-bottom: 20px; font-size: 14px;">资费概要（表格展示）</div>
                      <div v-for="(item,index) in all.summary" :key="index"  style="margin-bottom: 20px;">
                        <div style="margin-bottom: 10px;" class="kflexc">
                          <el-input v-model="item.name" style="width: 450px;" placeholder="请输入自定义名称"></el-input>
                          <i class="el-icon-delete" style="color: #56b0ff; cursor: pointer;" @click="shanchu1(item,index)"></i>
                        </div>
                        <wenzhanglei @changename="changename($event,item,index)" :height="'200'" :name="item.value" ref="wenzhanglei" v-if="relo"></wenzhanglei>
                      </div>
                      <div><el-button type="primary" plain @click="add">+ 添加自定义模块</el-button></div>
                    </div>

                    <div style="margin-bottom: 40px;" class="h200">
                      <div style="margin-bottom: 20px; font-size: 14px;">资费详情</div>
                      <div v-for="(item,index) in all.details" :key="index"  style="margin-bottom: 20px;">
                        <div style="margin-bottom: 10px;" class="kflexc">
                          <el-input v-model="item.name" style="width: 450px;" placeholder="请输入自定义名称"></el-input>
                          <i class="el-icon-delete" style="color: #56b0ff; cursor: pointer;" @click="shanchu2(item,index)"></i>
                        </div>
                        <wenzhanglei @changename="changename2($event,item,index)" :height="'200'" :name="item.value" ref="wenzhanglei" v-if="relo"></wenzhanglei>
                      </div>
                      <div><el-button type="primary" plain @click="add2">+ 添加自定义模块</el-button></div>
                    </div>

                    <div style="margin-bottom: 40px;" class="h200">
                      <div style="margin-bottom: 20px; font-size: 14px;">其他说明</div>
                      <div v-for="(item,index) in all.other" :key="index"  style="margin-bottom: 20px;">
                        <div style="margin-bottom: 10px;" class="kflexc">
                          <el-input v-model="item.name" style="width: 450px;" placeholder="请输入自定义名称"></el-input>
                          <i class="el-icon-delete" style="color: #56b0ff; cursor: pointer;" @click="shanchu3(item,index)"></i>
                        </div>
                        <wenzhanglei @changename="changename3($event,item,index)" :height="'200'" :name="item.value" ref="wenzhanglei" v-if="relo"></wenzhanglei>
                      </div>
                      <div><el-button type="primary" plain @click="add3">+ 添加自定义模块</el-button></div>
                    </div>
                  </div>

                  <div>
                    <div id="content" style="width: 750px; margin-left: 60px; min-height: 750px; padding: 0 20px 80px; position: relative; background: url('https://photo.91haoka.cn/mobanbeijingtu2.png') #56b0ff no-repeat;">
                      <div style="text-align: center; width: 100%; color: #fff; font-size: 52px; padding: 40px 0 30px; text-shadow: 4px 4px 10px rgb(86, 176, 255);">
                        {{all.name}}
                      </div>
                      <div style=" background: #fff; border-radius: 20px; padding: 20px;">
                        <div style="background: rgb(0, 159, 242); text-align: center; border: 4px solid rgb(0, 159, 242); border-radius: 20px; overflow: hidden;">
                          <div class="kflexc" style="border-bottom: 2px solid rgb(86, 176, 255);" v-for="(item,index) in all.summary" :key="index">
                            <div style="color: #fff; width: 200px; font-size: 26px;">{{item.name}}</div>
                            <div class="aaaa" style=" flex: 1; padding: 30px 0; background: #fff; font-size: 30px; font-weight: bold;" v-html="item.value">{{item.value}}</div>
                          </div>
                        </div>
                        <div v-for="(item,index) in all.details" :key="index">
                          <div style="font-size: 26px;  padding: 20px 0; font-weight: bold; color: #009FF2;">{{item.name}}</div>
                          <div style="font-size: 22px;  line-height: 36px;" v-html="item.value">{{item.value}}</div>
                        </div>
                      </div>
                      <div style=" background: #fff; border-radius: 20px; padding: 20px; margin-top: 30px;">
                        <div v-for="(item,index) in all.other" :key="index">
                          <div style="font-size: 26px;  padding: 20px 0; font-weight: bold; color: #009FF2;">{{item.name}}</div>
                          <div style="font-size: 22px;  line-height: 36px;" v-html="item.value">{{item.value}}</div>
                        </div>
                      </div>
                    </div>
                    <div class="kflexcc" style="margin-top: 30px;  margin-left: 60px;">
                      <el-button type="primary" plain :loading="loading" @click="fuzhi">复制</el-button>
                      <el-button type="primary" plain :loading="loading" @click="xiazai">下载</el-button>
                    </div>
                  </div>
                </div>
                <div class="kflexcc" style="margin-top: 30px;"><el-button type="danger" @click="shengchengtupian">保存</el-button></div>
    </div>
  </div>
</template>


<script>
  import * as qiniu from 'qiniu-js'
	import axios from 'axios'
	import top from '@/components/top.vue'
	import left from '@/components/left.vue'
  import wenzhanglei from '@/components/zujian/wenzhanglei.vue'


	export default{
		components: {
			"left": left,
			"top": top,
      wenzhanglei
		},
		name: 'daliangset',
		data(){
			return{
        all:{
          name:"",
          summary:[],
          details:[],
          other:[],
          thumb:"",
          id:''
        },
        relo:false,
        loading:true,
			}
		},
		created() {

		},
    mounted() {
      if(this.$route.query.id){
        axios.get(`/api/plan-market/tool/quick/picture/list?id=${this.$route.query.id}`)
        	.then(response => {
        		if (response.data.msg.code == 0) {
              this.all = response.data.data.data[0]

              // wenzhanglei

              this.$nextTick(()=>{
                this.relo = true
              })

              this.loading = false
        		} else {
              that.$message.error(response.data.msg.info);
        		}
        	})
      }else{
        this.relo = true
        this.loading = false
      }
    },
		methods:{

      shanchu1:function(item,index){
        this.all.summary.splice(index,1)
      },
      shanchu2:function(item,index){
        this.all.details.splice(index,1)
      },
      shanchu3:function(item,index){
        this.all.other.splice(index,1)
      },

      changename:function(e,item,index){
        this.all.summary[index].value = e
      },
      changename2:function(e,item,index){
        this.all.details[index].value = e
      },
      changename3:function(e,item,index){
        this.all.other[index].value = e
      },

      dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },

      getRandomChar:function(len = 11)  {
        var  x = "0123456789qwertyuioplkjhgfdsazxcvbnm" // 需要什么字符这里添加
        var  tmp = ""
        var timestamp = new Date().getTime();
        for(var  i=0;i<len;i++)  {
          tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
        }
        return  timestamp+tmp;
      },

      uploadok: function(file) {
        let name = this.getRandomChar()
        var that = this
        axios.get(`/api/system/qiniu/upload_token2`,{params:{bucket:'test91'}})
          .then(response => {
            if(response.data.msg.code == 0){

              const observer = {
                next(res){},
                error(err){},
                complete(res){

                  that.all.thumb = 'https://test91.91haoka.cn/'+ res.data

                  axios.post(`/api/plan-market/tool/quick/picture/update`,that.all)
                  	.then(response => {
                  		if (response.data.msg.code == 0) {

                        that.$message.success('保存成功');
                        that.loading = false
                        that.$router.back(-1)

                  		} else {
                        that.$message.error(response.data.msg.info);
                  		}
                  	})

                }
              }
              const observable = qiniu.upload(file, name, response.data.data, {}, {})
              const subscription = observable.subscribe(observer) // 上传开始

            }else{
              this.$message.error(response.data.msg.info);
            }
          });


      },

      shengchengtupian: function() {
        this.loading = true
        var element2 = document.getElementById('content');
        html2canvas(element2, {
          useCORS: true, // 这个选项会自动处理跨域问题
          // scale: 1,//图片清晰度，越高越清楚，图片质量越大
          backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        }).then(canvas => {
          let base64 = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的base64图片

          let file = this.dataURLtoFile(base64, Date.parse(Date()) + ".jpg");

          this.uploadok(file)



          // 将图像添加到DOM中
          // var a = document.createElement("a");
          // document.body.appendChild(a);
          // a.href = canvas.toDataURL('image/png');
          // a.download = "";
          // a.click();
        });
      },

      add:function(){
        this.all.summary.push({
          name:"",
          value:""
        })
      },
      add2:function(){
        this.all.details.push({
          name:"",
          value:""
        })
      },
      add3:function(){
        this.all.other.push({
          name:"",
          value:""
        })
      },

      xiazai:function(){
        this.loading = true
        var element2 = document.getElementById('content');
        html2canvas(element2, {
          useCORS: true, // 这个选项会自动处理跨域问题
          // scale: 1,//图片清晰度，越高越清楚，图片质量越大
          backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        }).then(canvas => {
          let base64 = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的base64图片
          let file = this.dataURLtoFile(base64, Date.parse(Date()) + ".jpg");

          // 将图像添加到DOM中
          var a = document.createElement("a");
          document.body.appendChild(a);
          a.href = canvas.toDataURL('image/png');
          a.download = "";
          a.click();

          this.loading = false
        });
      },

      fuzhi:function(){

        this.loading = true

        let file = ''

        var element2 = document.getElementById('content');
        html2canvas(element2, {
          useCORS: true, // 这个选项会自动处理跨域问题
          // scale: 1,//图片清晰度，越高越清楚，图片质量越大
          backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        }).then(canvas => {
          let base64 = canvas.toDataURL("image/jpeg", 0.8); // 压缩后的base64图片
          file = this.dataURLtoFile(base64, Date.parse(Date()) + ".jpg");

          let name = this.getRandomChar()
          var that = this
          axios.get(`/api/system/qiniu/upload_token2`,{params:{bucket:'test91'}})
            .then(response => {
              if(response.data.msg.code == 0){
                const observer = {
                  next(res){},
                  error(err){},
                  complete(res){
                    const imageUrl = 'https://test91.91haoka.cn/'+ res.data
                    fetch(imageUrl)
                      .then(response => response.blob())
                      .then(blob => {
                        // 创建一个临时 img 元素
                        const img = new Image();
                        img.src = URL.createObjectURL(blob);

                        img.onload = () => {
                          // 创建一个 canvas 元素
                          const canvas = document.createElement('canvas');
                          canvas.width = img.width;
                          canvas.height = img.height;

                          // 将图片绘制到 canvas 上
                          const ctx = canvas.getContext('2d');
                          ctx.drawImage(img, 0, 0);

                          // 将 canvas 内容转换为 PNG 格式的 Blob
                          canvas.toBlob(pngBlob => {
                            // 创建一个 ClipboardItem 对象，使用 image/png 类型

                            if (navigator.clipboard) {
                              const clipboardItem = new ClipboardItem({ 'image/png': pngBlob });

                              // 将图片复制到剪贴板
                              navigator.clipboard.write([clipboardItem])
                                .then(() => {
                                  that.loading = false
                                  that.$message.success('图片已成功复制到剪贴板');
                                })
                                .catch(err => {
                                  that.loading = false
                                  that.$message.error('无法复制图片到剪贴板:', err);
                                });
                            } else {
                              that.loading = false
                              that.$message.error('无法复制图片到剪贴板:', err);
                            }
                          }, 'image/png'); // 指定输出为 PNG 格式
                        };
                      })
                      .catch(err => {
                        that.loading = false
                        console.error('无法获取图片:', err);
                      });

                  }
                }
                const observable = qiniu.upload(file, name, response.data.data, {}, {})
                const subscription = observable.subscribe(observer) // 上传开始

              }else{
                this.$message.error(response.data.msg.info);
              }
            });

        });
      },

		}

	}
</script>

<style lang="scss" scoped>
   @import "@/assets/zuixin.scss";

   /deep/ p {
     margin-block-start: 0px;
     margin-block-end: 0px;
   }
   /deep/ .h100{
     .w-e-text-container{ height: 100px !important;}
   }
   /deep/ .h200{
     .w-e-text-container{ height: 200px !important;}
   }
</style>
